<?php
namespace app\common\base;

use think\Db;
use app\common\traits\ErrorRecord;

class Apibio
{
	use ErrorRecord;

    public function __construct()
    {
        if(1) {
        	$key_server_params = array(
                'client' => 'client03',
                'key'    => 'hM4uZcGs9d',
        	);
        } else {
        	$key_server_params = array(
            	'client' => 'client01',
            	'key'    => '1ZYw71APsQ',
            );
        }

        $this->_key_params = $key_server_params;
    }

    /*
     * run
     */
    public function run($url, $data)
    {
        $param_string       = http_build_query($data);
        $this->_request_url = $url;

        $signature_param    = $this->signature();
        $this->_data        = $signature_param . '&' . $param_string;

        if (false === $response = $this->postData()) {
            return false;
        }

        if (false === $response['success']) {
            $this->_error = $response['info'];
            return false;
        }

        return $response;
    }

    /**
     * POST请求数据
     *
     * @param    string
     *
     * @return   string
     **/
    private function postData()
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->_request_url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $this->_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 180);

        $res = curl_exec($ch);
        if ($error = curl_error($ch)) {
            $this->_error = curl_error($ch);
            return false;
        }

        curl_close($ch);
        if (json_decode($res, true) == '') {
            return array('success' => false, 'info' => $res);
        }
        $res = json_decode($res, true);
        return $res;
    }

    /**
     * 签名
     *
     * @return   string
     **/
    private function signature()
    {
        $params = array(
            'client'    => $this->_key_params['client'],
            'nonce'     => rand(1000, 10000),
            'timestamp' => time(),
        );

        $signature_params = array(
            'key'       => $this->_key_params['key'],
            'timestamp' => $params['timestamp'],
            'nonce'     => $params['nonce'],
        );
        sort($signature_params, SORT_STRING);
        $params['signature'] = sha1(join('', $signature_params));
        return htmlspecialchars(http_build_query($params));
    }

}